package com.siha_back.controller;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.siha_back.common.Result;
import com.siha_back.utils.DifyApiClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/dify")
public class DifyController {
    private final DifyApiClient difyClient;
    private final ObjectMapper mapper = new ObjectMapper();

    @Autowired
    public DifyController(@Value("${dify.api-key}") String apiKey) {
        this.difyClient = new DifyApiClient(apiKey);
    }

    @GetMapping("/generate")
    public Result generateText(@RequestParam String text) {
        try {
            // 1. 构建请求体
            ObjectNode requestBody = buildRequestBody(text);

            // 2. 调用Dify API
            String response = difyClient.post("/workflows/run", requestBody.toString());

            // 3. 处理并合并所有text_chunk
            return Result.success(200,"请求成功",Arrays.stream(response.split("\n\n"))
                    .filter(event -> event.startsWith("data: "))
                    .map(event -> {
                        try {
                            JsonNode json = mapper.readTree(event.substring(6));
                            if ("text_chunk".equals(json.path("event").asText())) {
                                return json.path("data").path("text").asText();
                            }
                            return "";
                        } catch (Exception e) {
                            return "";
                        }
                    })
                    .collect(Collectors.joining()));

        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    private ObjectNode buildRequestBody(String text) {
        ObjectNode requestBody = mapper.createObjectNode();
        ObjectNode inputs = mapper.createObjectNode();
        inputs.put("text", text);
        inputs.put("tsc", "你是一位有多年经验的java后端开发面试官...");
        requestBody.set("inputs", inputs);
        requestBody.put("response_mode", "streaming"); // 保持流式请求但同步返回
        requestBody.put("user", "abc-123");
        return requestBody;
    }
}
